package org.ledeange.textflow;

import org.apache.commons.lang.StringUtils;
import org.ledeange.textflow.exceptions.TextFlowException;

/**
 * Generic Field, containing commons properties.
 * 
 * @author leonardo
 *
 */
public abstract class AbstractField implements Field {

  protected Integer length;

  protected Alignment align;

  private char paddingChar = ' ';

  public int getLength() {
	  return this.length;
  }

  public void setLength(Integer length) {
	  this.length = length;
  }

  public Alignment getAlign() {
	  return this.align;
  }

  public void setAlignment(Alignment align) {
	  this.align = align;
  }

  public char getPaddingChar() {
	  return paddingChar;
  }

  public void setPaddingChar(char paddingChar) {
	  this.paddingChar = paddingChar;
  }

  /**
   * Perform the unmarshall of the string contained
   * in a single field of the row.
   */
  public Object readStringField(String field) {
	  return null;
  }

  /**
   * Performs the marshalling of the single field.
   * Checks of length and padding are executed after
   * the call to the specialized method to read the
   * object.
   */
  public String createStringField(Object object) throws TextFlowException {
	  String result ;
	  assert (object instanceof String);
	  
	  result = this.createString(object);
	  if (length!=null || result.length()< length) {
		  // DEVO FORMATTARE LA STRINGA
		  if (Alignment.LEFT.equals(align)) {
			  result = StringUtils.leftPad(result, length, paddingChar);
		  } else if (Alignment.RIGHT.equals(align)) {
			  result = StringUtils.rightPad(result, length, paddingChar);
		  }
	  }
	  
	  return result;
  }
  
  
  public void setState(Object Object) {
  }
  
  /**
   * This method is used during the unmarshalling of 
   * the row of the textfield and is used to unmarshall
   * the single field of the row read.
   * 
   * @param string
   * @return
   */
  abstract protected Object readString(String string);

  /**
   * Used during marshalling of the object contained in
   * an array of the row.
   * This method is called during marshalling process.
   * 
   * @param object
   * @return
   * @throws TextFlowException
   */
  abstract protected String createString(Object object) throws TextFlowException ;
}